#### Deming Regressions ####

# Functions
deming_mod = \(data, agree_in, redist_in){
  if(redist_in == "Pooled"){
    dem_mod = deming::deming(effect_0 ~ effect_1, 
                             data = data |> filter(agree == agree_in),
                             weights = N_obs, xstd = se_1, ystd = se_0)
  } else {
    dem_mod = deming::deming(effect_0 ~ effect_1, 
                             data = data |> filter(agree == agree_in,
                                                   is_redist == redist_in),
                             weights = N_obs, xstd = se_1, ystd = se_0)
  }
  data.frame(
    agree = agree_in,
    redist = redist_in,
    dem_slope = dem_mod$coefficients[2],
    dem_ci_low = dem_mod$ci[2,1],
    dem_ci_upp = dem_mod$ci[2,2]
  )
}

run_deming = \(data, demo){
  # Define Redist Policies
  econ = c("gov_insurance", "public_option", "health_subsidies",
           "mctaxes", "estate_tax", "uctaxes", "college",
           "trade", "minwage", "gauranteed_jobs", "right_to_work",
           "medicare_for_all", "uctaxes2", "abolish_priv_insurance",
           "china_tariffs", "forgive_debt", "wealth_tax","housing_guarantee")
  # Reshape data
  dem_dat = data |> 
    select(condition, group, effect, se, N_obs, agree) |>
    pivot_wider(id_cols = c("condition","agree"),
                names_from = group, 
                values_from = c("effect","se","N_obs")) |> 
    mutate(N_obs = N_obs_1 + N_obs_0,
           is_redist = as.character(condition %in% econ))
  # Run models
  vars = expand.grid(c("Pooled", "TRUE","FALSE"),
              c("Agree","Disagree"))
  map2_dfr(vars$Var2,vars$Var1, ~ deming_mod(data = dem_dat, agree = .x, redist = .y)) |> 
    mutate(demo = demo) |> 
    remove_rownames()
}

# Load Data
fig4_dat = bind_rows(import(here("data","fig4_inc_agree_dat.rds")) |> 
                       mutate(agree = "Agree"),
                     import(here("data","fig4_inc_disagree_dat.rds")) |> 
                       mutate(agree = "Disagree")) |> 
  invert_group()

fig6_dat = bind_rows(import(here("data","fig6_edu_agree_dat.rds")) |> 
                       mutate(agree = "Agree"),
                     import(here("data","fig6_edu_disagree_dat.rds")) |> 
                       mutate(agree = "Disagree")) |>
  invert_group()

fig8_dat = bind_rows(import(here("data","fig8_r_edu_agree_dat.rds")) |> 
                       mutate(agree = "Agree"),
                     import(here("data","fig8_r_edu_disagree_dat.rds")) |> 
                       mutate(agree = "Disagree")) |> 
  invert_group()

deming_df = bind_rows(
  run_deming(fig4_dat, "Income"),
  run_deming(fig6_dat, "Education"),
  run_deming(fig8_dat, "Education (Republican)")
) |> 
  mutate(across(where(is.numeric), ~round(.x, 2)),
         redist = case_match(
           redist,
           "Pooled" ~ "Pooled",
           "TRUE" ~ "Redistributive",
           "FALSE" ~ "Non-Redistributive"
         ),
         demo_agree = paste0(demo, agree),
         dem_est = paste0(dem_slope,"\n(",
                          dem_ci_low,", ",dem_ci_upp,")") |> 
           linebreak()) |> 
  pivot_wider(id_cols = redist, names_from = demo_agree, values_from = dem_est)

kable(deming_df,
      col.names = c("Policy Class","Agree","Disagree",
                    "Agree","Disagree", "Agree","Disagree"),
      format = 'latex', booktabs = T) |> 
  kable_classic(full_width = F) |> 
  add_header_above(c(" " = 1, "Income" = 2, "Education" = 2, "Education (Rep.)" = 2)) |> 
  fix_table() |> 
  writeLines(here("tables","appendix","tab_s8.tex"))

ccat("See 'tab_s8.tex' for Table S8 output")
